<template>
  <div>
    <div>
      <!-- 绑定数据 data -->
      <!-- 改变绑定值 props -->
      <!-- 默认全部展开 -->
      <el-tree
        ref="tree"
        v-loading="loading"
        :data="permissionList"
        :props="{label:'name'}"
        default-expand-all
        :show-checkbox="true"
        :check-strictly="true"
        node-key="id"
        min-height="300px"
      />
    </div>

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button
          size="small"
          type="primary"
          @click="setRolesBtn"
        >确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { getRoleId, assignPerm } from '@/api/setting'

import { tranListToTreeData } from '@/utils'
export default {
  name: 'AssignPermission',
  props: {
    roleId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      permissionList: [], // 权限列表
      loading: false
    }
  },
  created() {
    this.getPermissionList()

    this.getRoleId()
  },

  methods: {
    // 获取树形结构列表
    async getPermissionList() {
      const res = await getPermissionList()
      console.log(res)
      this.permissionList = tranListToTreeData(res.data)
    },

    // 获取角色已有权限
    async getRoleId() {
      this.loading = true
      const res = await getRoleId(this.roleId)
      console.log(res)

      this.$refs.tree.setCheckedKeys(res.data.permIds)
      this.loading = false
    },

    // 点击取消事件
    async cancelButton() {
      this.$emit('close')
    },

    // 点击确定事件
    async setRolesBtn() {
      // 获取tree 提供的 已勾选节点
      const permIds = this.$refs.tree.getCheckedKeys()
      const res = await assignPerm({
        id: this.roleId,
        permIds

      })
      console.log(res)
      // 提示
      this.$message.success(res.message)
      // 关闭弹框
      this.$emit('close')
    }
  }
}
</script>

<style>
</style>
